package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import sun.security.krb5.internal.AuthContext;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author dyqstart
 * @create 2021-08-16-18:10
 * @since 1.0.0
 */
@RequestMapping("/api/user")
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/address/list")
    public List<UserAddress> getCurrentUserAddress(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        return userService.getUserAddressListByUserId(userId);
    }

    @PostMapping("/passport/login")
    public Result login(@RequestBody UserInfo userInfo,
                        HttpServletRequest request){

        UserInfo userInfoResult = userService.login(userInfo);


        /**
         * 1、给Result里面返回这个数据
         * 2、map
         *  2、1 token
         *  2。2 nickname
         */
        if (userInfoResult == null){
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }

        //登陆成功
        Map<String,Object> success = userService.handleLoginSuccess(userInfoResult,request);

        return Result.ok(success);
    }

    @GetMapping("/passport/logout")
    public Result logout(@RequestHeader(value = "token",required = false) String headerToken,
                         @CookieValue(value = "token",required = false) String cookieToken){

        String token = headerToken;
        if (StringUtils.isEmpty(token)){
            token = cookieToken;
        }

        userService.logout(token);

        return Result.ok();
    }
}
